import { AxiosRequestConfig } from "axios";
import AxiosRequest from "../axiosRequest";
import { ReturnPlugin, YFWRequestOptions } from "../types";

export function RetryPlugin(
  requestIns: AxiosRequest,
  options: YFWRequestOptions
): ReturnPlugin {
  const { retryCount, retryInterval } = options

  if (!retryCount) {
    return {};
  }
  requestIns.pluginStore.retryCount = 0
  return {
    onBefore: () => {
      //  console.log('onBefore');
    },
    onSuccess: () => {
      console.log('onSuccess');
      requestIns.pluginStore.retryCount = 0
    },
    onError: () => {
      requestIns.pluginStore.retryCount += 1
      console.log('onError', requestIns.pluginStore.retryCount, retryCount);
      if (requestIns.pluginStore.retryCount < retryCount) {
        const timeout = retryInterval || 2000;
        requestIns.pluginStore.retryTimer = setTimeout(() => {
            requestIns.refresh()
        }, timeout)
      } else {
        requestIns.pluginStore.retryCount = 0;
      }
    },
    onCancel: () => {
      requestIns.pluginStore.retryCount = 0
      if (requestIns.pluginStore.retryTimer) {
        clearTimeout(requestIns.pluginStore.retryTimer)
      }
    }
  }
}
